<?php
namespace app\push\controller;
use app\common\model\ChatClient;
use app\facade\Aes;
use think\worker\Server;
class WebWorker extends Server{
	protected $socket = 'websocket://0.0.0.0:2345';
	/**
	 * 收到信息
	 * @param $connection
	 * @param $data
	 */
	public function onMessage($connection, $data)
	{
		$data  = explode(',',$data);
		parse_str(Aes::decrypt($data[0]), $user);
		$where[] =['uid','eq',$user['id']];
		$where[] =['room_id','eq',$data[1]];
		$info = ChatClient::field('id,client_id')->where($where)->find();
		if($info){
			$info->client_id = $connection;
			$info->save();
		}else{
			$arr = array(
				'uid'=>$user['id'],
				'room_id'=>$data[1],
				'client_id'=>$connection,
			);
			ChatClient::create($arr);
		}
		$connection->send('我收到你的信息了');
	}
	/**
	 * 当连接建立时触发的回调函数
	 * @param $connection
	 */
	public function onConnect($connection)
	{
		file_put_contents('worker11.txt',$connection);
	}
	/**
	 * 当连接断开时触发的回调函数
	 * @param $connection
	 */
	public function onClose($connection)
	{

	}    /**
 * 当客户端的连接上发生错误时触发
 * @param $connection
 * @param $code
 * @param $msg
 */
	public function onError($connection, $code, $msg)
	{
		echo "error $code $msg\n";
	}
	/**
	 * 每个进程启动
	 * @param $worker
	 */
	public function onWorkerStart($worker)
	{

	}
}
